package com.yiren.dbaa.module.common.model;

import android.app.Activity;

import com.blankj.utilcode.util.FileUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yiren.backstage.config.api.LoadConfigApi;
import com.yiren.backstage.config.bean.device.StationParamConfigBean;
import com.yiren.backstage.config.bean.device.UserParamConfigBean;
import com.yiren.backstage.currency.bean.UserInfoBean;
import com.yiren.backstage.currency.constant.DbConstant;
import com.yiren.backstage.db.dao.cache.DataCache;
import com.yiren.backstage.db.dao.cache.interf.DataCacheStateCallBack;
import com.yiren.backstage.db.dao.controller.UserDbController;
import com.yiren.dbaa.constant.AddressConstant;
import com.yiren.dbaa.currency.api.CommonCallBack;
import com.yiren.dbaa.module.common.bean.AppScanLoginBean;
import com.yiren.dbaa.module.common.bean.LoginQrcodeBean;
import com.yiren.dbaa.module.common.bean.LoginRemoteBean;
import com.yiren.dbaa.module.common.bean.UserConfigBean;
import com.yiren.dbaa.module.common.contract.MainContract;
import com.yiren.dbaa.module.param_config.api.ParamConfigApi;
import com.yiren.dbaa.net.OkHttpUtils;
import com.yiren.dbaa.net.bean.BaseResponseBean;
import com.yiren.dbaa.net.bean.SimCardInfoBean;
import com.yiren.dbaa.net.interf.StringCallback;
import com.yiren.dbaa.util.AssetCopyUtil;
import com.yiren.dbaa.util.PhoneInfoUtil;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lwb
 * @date : 2022/7/4 11:45
 * @description: 首页M
 */
public class MainModel implements MainContract.Model {

    private Activity activity;
    private Gson gson;
    private UserParamConfigBean userParamConfig;
    private boolean isCopyer;

    public MainModel(Activity activity) {
        this.activity = activity;
        gson = new Gson();
        userParamConfig = LoadConfigApi.loadUserParamConfig(activity);
    }

    @Override
    public void getSimCardInfo(CommonCallBack callBack) {
        PhoneInfoUtil phoneInfoUtil = new PhoneInfoUtil(activity);
        String iccid = phoneInfoUtil.getIccid();
        Map<String, Object> map = new HashMap<>();
        map.put("iccid", iccid);
        OkHttpUtils.getInstance().postJsonString(activity, AddressConstant.getSimCardInfoByIccid(), gson.toJson(map), new StringCallback() {
            @Override
            public void getString(String result) {
                BaseResponseBean<SimCardInfoBean> responseBean = gson.fromJson(result, new TypeToken<BaseResponseBean<SimCardInfoBean>>() {
                }.getType());
                if (responseBean.getError() == null) {
                    SimCardInfoBean simCardInfoBean = responseBean.getResult();
                    String equipmentId = simCardInfoBean.getEquipmentId();
                    StationParamConfigBean stationParamConfigBean = LoadConfigApi.loadStationParamConfig(activity);
                    stationParamConfigBean.setHostNumber(equipmentId);
                    ParamConfigApi.saveStationParamConfig(activity, stationParamConfigBean);
                    callBack.success(equipmentId);
                }
            }

            @Override
            public void getFail() {
                String deviceNumber = LoadConfigApi.loadStationParamConfig(activity).getHostNumber();
                callBack.success(deviceNumber);
            }
        });
    }

    @Override
    public void getCoachLoginQrCode(CommonCallBack callBack) {
        OkHttpUtils.getInstance().getStringByAsync(activity, AddressConstant.getLoginQrCodeUrl(), new StringCallback() {
            @Override
            public void getString(String result) {
                BaseResponseBean<LoginQrcodeBean> responseBean = gson.fromJson(result, new TypeToken<BaseResponseBean<LoginQrcodeBean>>() {
                }.getType());
                if (responseBean.getError() == null) {
                    callBack.success(responseBean.getResult());
                } else {
                    callBack.fail(responseBean.getError().getMessage());
                }
            }
        });
    }

    @Override
    public void checkCoachSweepCode(String code, CommonCallBack callBack) {
        OkHttpUtils.getInstance().getStringByAsync(activity, AddressConstant.getLoginStatusUrl("?code=" + code), new StringCallback() {
            @Override
            public void getString(String result) {
                BaseResponseBean<AppScanLoginBean> responseBean = gson.fromJson(result, new TypeToken<BaseResponseBean<AppScanLoginBean>>() {
                }.getType());
                AppScanLoginBean appScanLogin = responseBean.getResult();
                if (null != appScanLogin) {
                    if (null == responseBean.getError()) {
                        userParamConfig.setAccessToken(appScanLogin.getToken());
                        ParamConfigApi.saveUserParamConfig(activity, userParamConfig);
                        callBack.success(appScanLogin);
                    } else {
                        callBack.fail(responseBean.getError().getMessage());
                    }
                } else {
                    callBack.complete();
                }
            }
        });
    }

    @Override
    public void postMapLogin(String phone, String password, CommonCallBack callBack) {
        Map<String, Object> map = new HashMap<>();
        map.put("grant_type", "password");
        map.put("login_type", "0");
        map.put("password", password);
        map.put("username", phone);
        OkHttpUtils.getInstance().postMapLoginAsync(activity, AddressConstant.getLoginUrl(), map, new StringCallback() {
            @Override
            public void getString(String result) {
                LoginRemoteBean t = gson.fromJson(result, new TypeToken<LoginRemoteBean>() {
                }.getType());
                if (t == null) {
                    callBack.fail("服务器请求出错，请重试！");
                } else {
                    // 后台登录接口没写好，先走之前的登录流程
                    userParamConfig.setAccessToken(t.getAccess_token());
                    userParamConfig.setRefreshToken(t.getRefresh_token());
                    userParamConfig.setName(phone);
                    ParamConfigApi.saveUserParamConfig(activity, userParamConfig);
                    callBack.success(result);
                }
            }
        });
    }

    @Override
    public void getUserInfo(CommonCallBack callBack) {
        OkHttpUtils.getInstance().getStringByAsync(activity, AddressConstant.getUserProfile(), new StringCallback() {
            @Override
            public void getString(String result) {
                BaseResponseBean<UserConfigBean> responseBean = gson.fromJson(result, new TypeToken<BaseResponseBean<UserConfigBean>>() {
                }.getType());
                if (responseBean.getError() == null) {
                    UserConfigBean userConfigBean = responseBean.getResult();
                    callBack.success(userConfigBean);
                } else {
                    callBack.fail(responseBean.getError().getMessage());
                }
            }

            @Override
            public void getFail() {
                callBack.fail("获取用户信息失败");
            }
        });
    }

    @Override
    public void saveUserInfo2Local(UserConfigBean userConfigBean) {
        UserInfoBean userInfo = userConfigBean.getUser();
        userInfo.setpUserId(5243);
        userParamConfig.setUserInfo(userInfo);
        userParamConfig.setPartner(userConfigBean.isPpaternerInfo());
        userParamConfig.setHasGjdInterface(userConfigBean.isHighOrderInfo());
        userParamConfig.setUserDeviceStatus(userConfigBean.getUes());
        if (null != userConfigBean.getEquipment()) {
            userParamConfig.setUserDeviceInfo(gson.toJson(userConfigBean.getEquipment()));
        }
        ParamConfigApi.saveUserParamConfig(activity, userParamConfig);
    }

    @Override
    public boolean checkUserDb() {
        if (null != userParamConfig.getUserInfo()) {
            // 获取用户信息后赋值user数据路径，检测user文件有效性
            DbConstant.USER_DATA_URL = AddressConstant.App_Main_Directory() + userParamConfig.getUserInfo().getId() + "/" + DbConstant.USER_DATA_NAME;
            if (!FileUtils.isFileExists(DbConstant.USER_DATA_URL)) {
                AssetCopyUtil assetCopyer = new AssetCopyUtil(activity);
                try {
                    isCopyer = assetCopyer.copyToPath(AddressConstant.App_Main_Directory(), userParamConfig.getUserInfo().getId() + "/" + DbConstant.USER_DATA_NAME, "data/user/user.db");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                isCopyer = true;
            }
            UserDbController.getInstance(true);
        }
        if (null != userParamConfig.getSite()) {
            DataCache.refreshAllCache(activity, userParamConfig.getSite(), new DataCacheStateCallBack.Callback() {
                @Override
                public void success() {
                }
            });
        }
        return isCopyer;
    }

    @Override
    public void clearUserInfo() {
        //如果是会话超时需要在点登录的时候清空当前的数据
        UserParamConfigBean userParamConfig = LoadConfigApi.loadUserParamConfig(activity);
        userParamConfig.setAccessToken("");
        userParamConfig.setRefreshToken("");
        userParamConfig.setUserInfo(null);
        ParamConfigApi.saveUserParamConfig(activity, userParamConfig);
    }
}
